package com.yanqu.road.server.manager.cross.battle;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangAutoResult;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangMonsterData;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangPatrons;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangStrongPoint;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangUserData;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.player.ReturnData;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.scene.UserScene;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.pb.HuaShiGangPb;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.huashigang.HuaShiGangProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.cross.battle.enums.HuaShiGangBuildMode;
import com.yanqu.road.server.manager.cross.battle.enums.HuaShiGangModeConnection;
import com.yanqu.road.server.manager.cross.battle.enums.eHuaShiGangModeType;
import com.yanqu.road.server.manager.scene.CrossSceneMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wpj
 * @Date 2020/9/28
 */
public class HuaShiGangMgr extends TempCrossMgr {

    public static Logger huaShiGangLogger = LogManager.getLogger(HuaShiGangMgr.class.getName());

    public static final int HuaShiGangModeLine = 3;

    public static Map<Integer, Point> pointMap;

    public static Map<Integer, Point> getPointMap() {
        return pointMap;
    }

    public static Map<Integer, HuaShiGangActivity> huaShiGangActivityMap;

    public static Map<Integer, HuaShiGangActivity> getHuaShiGangActivityMap() {
        return huaShiGangActivityMap;
    }

    public static void setHuaShiGangActivityMap(Map<Integer, HuaShiGangActivity> huaShiGangActivityMap) {
        HuaShiGangMgr.huaShiGangActivityMap = huaShiGangActivityMap;
    }

    public static HuaShiGangUserData getHuaShiGangUserData(int activityId, long serverId, long userId) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            return null;
        }

        return huaShiGangActivity.getUserData(serverId, userId);
    }

    /**
     * 获取花石纲数据
     *
     * @param activityId
     * @return
     */
    public static synchronized  HuaShiGangActivity getHuaShiGangActivity(int activityId) {
        if (huaShiGangActivityMap.get(activityId) == null) {
            // 读配置 获取活动信息 保证有活动信息
            ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
            if (activityInfo == null) {
                return null;
            }
            HuaShiGangActivity huaShiGangActivity = new HuaShiGangActivity(activityInfo);
            huaShiGangActivityMap.put(activityId, huaShiGangActivity);
            // 添加场景
            CrossSceneMgr.initActivity(activityInfo);
        }

        return huaShiGangActivityMap.get(activityId);
    }

    /**
     * 重新加载花石纲配置
     * @param activityId
     */
    public static void reloadHuaShiGangConfig(int activityId) {
        HuaShiGangActivity activity = huaShiGangActivityMap.get(activityId);
        if (activity != null) {
            activity.reloadConfig();
        }
    }

    /**
     * 修复代码
     */
    public static void repair(int activityId) {
        HuaShiGangActivity activity = huaShiGangActivityMap.get(activityId);
        if (activity != null) {
            activity.repair();
        }
    }

    /**
     * 获取花石纲活动
     *
     * @param activityInfo
     * @return
     */
    public static synchronized HuaShiGangActivity getHuaShiGangActivity(ActivityInfo activityInfo) {
        if (huaShiGangActivityMap.get(activityInfo.getActivityId()) == null) {
            // 读配置 获取活动信息
            HuaShiGangActivity huaShiGangActivity = new HuaShiGangActivity(activityInfo);
            huaShiGangActivityMap.put(activityInfo.getActivityId(), huaShiGangActivity);
            // 添加场景
            CrossSceneMgr.initActivity(activityInfo);
        }

        return huaShiGangActivityMap.get(activityInfo.getActivityId());
    }

    /**
     * 选择下一个坐标
     *  @param activityId
     * @param serverId
     * @param playerId
     * @param x
     * @param y
     * @param patronsList
     * @param userBaseInfo
     */
    public static void chooseNextPoint(int activityId, long serverId, long playerId, int x, int y, List<Integer> patronsList, int goldenKeyNum, UserBaseInfo userBaseInfo, long totalAbility) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.ChooseNextPointRespMsg.Builder builder = HuaShiGangProto.ChooseNextPointRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_CHOOSE_NEXT_POINT, builder));
            return;
        }
        int ret = huaShiGangActivity.chooseNextPoint(serverId, playerId, x, y, patronsList, goldenKeyNum, userBaseInfo, totalAbility);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_CHOOSE_NEXT_POINT, builder));
            return;
        } else {
            builder.setRet(0);
            // 拼装数据
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_CHOOSE_NEXT_POINT, builder));
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_USER_DATA_NOTIFY, getHuaShiUserDataGangRespMsg(activityId, serverId, playerId)));
        }
    }

    /**
     * 自动处理下一个坐标
     */
    public static void autoHandleNextPoint(int activityId, long serverId, long playerId, int x, int y, int goldenKeyNum, UserBaseInfo userBaseInfo,
                                           List<Integer> patronsList, List<Long> abilityList, List<Integer> additionList, long totalAbility) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.AutoHandleNextPointRespMsg.Builder builder = HuaShiGangProto.AutoHandleNextPointRespMsg.newBuilder();
        builder.setRet(0);
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_AUTO_HANDLE_NEXT_POINT, builder));
            return;
        }
        HuaShiGangUserData userData = huaShiGangActivity.getUserData(serverId, playerId);
        if (userData == null || !userData.getTransportList().contains(1)) {
            builder.setRet(GameErrorCode.E_HUA_SHI_GANG_TRANSPORT_LOCK);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_AUTO_HANDLE_NEXT_POINT, builder));
            return;
        }
        int ret = 0;
        if (userData.getX() != x || userData.getY() != y) {
            ret = huaShiGangActivity.chooseNextPoint(serverId, playerId, x, y, patronsList, goldenKeyNum, userBaseInfo, totalAbility);
        }
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_AUTO_HANDLE_NEXT_POINT, builder));
            return;
        }
        // 处理事件
        HuaShiGangAutoResult result = huaShiGangActivity.autoCompleteNextPointEvent(serverId, playerId, userBaseInfo,
                patronsList, abilityList, additionList);
        // 同步玩家数据
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_USER_DATA_NOTIFY, getHuaShiUserDataGangRespMsg(activityId, serverId, playerId)));
        // 通知区服后续处理
        if (result.getRet() == 0) {
            builder.setStopReason(result.getStopReason());
            builder.setEventType(result.getEventType());
            builder.setEventId(result.getEventId());
            builder.setReward(result.getReward());
            builder.setConsume(result.getConsume());
            builder.setPatronsId(result.getPatronsId());
            builder.setPatronsAdd(result.getPatronsAdd());
            builder.setBoxStatus(result.getBoxStatus());
            HuaShiGangProto.CrossAutoHandleNextPointRespMsg.Builder respMsg = HuaShiGangProto.CrossAutoHandleNextPointRespMsg.newBuilder();
            respMsg.setActivityId(activityId);
            respMsg.setRespMsg(builder);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(GameProtocol.S_HUA_SHI_GANG_AUTO_HANDLE_NEXT_POINT_FROM_CROSS, respMsg));
        } else {
            builder.setRet(result.getRet());
            builder.setConsume(result.getConsume());
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_AUTO_HANDLE_NEXT_POINT, builder));
        }
    }

    /**
     * 获取花石纲用户数据包
     * @return
     */
    public static HuaShiGangProto.GetHuaShiGangUserDataRespMsg.Builder getHuaShiUserDataGangRespMsg(int activityId, long serverId, long playerId) {
        HuaShiGangUserData huaShiGangUserData =  HuaShiGangMgr.getHuaShiGangUserData(activityId, serverId, playerId);
        HuaShiGangProto.GetHuaShiGangUserDataRespMsg.Builder notifyBuilder = HuaShiGangProto.GetHuaShiGangUserDataRespMsg.newBuilder();
        if (huaShiGangUserData == null) {
            notifyBuilder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
        } else {
            notifyBuilder.setRet(0);
            notifyBuilder.setX(huaShiGangUserData.getX());
            notifyBuilder.setY(huaShiGangUserData.getY());
            notifyBuilder.setIsFinish(huaShiGangUserData.isFinish());
            notifyBuilder.setMonsterId(huaShiGangUserData.getMonsterId());
            notifyBuilder.addAllPatronsId(huaShiGangUserData.getRandomPatronsId());
            if (huaShiGangUserData.getPatronsMap().size() > 0) {
                for (HuaShiGangPatrons patrons : huaShiGangUserData.getPatronsMap().values()) {
                    HuaShiGangProto.HuaShiGangPatronsAdditionEntity.Builder entity = HuaShiGangProto.HuaShiGangPatronsAdditionEntity.newBuilder();
                    entity.setPatronsId(patrons.getPatId());
                    entity.setAddition(patrons.getAddition());
                    entity.setBossAttackTimes(patrons.getBatMap().getOrDefault(huaShiGangUserData.getY(), 0));
                    entity.setNormalAttackTimes(patrons.getNat());
                    notifyBuilder.addAddition(entity);
                }
            }
            for (Map.Entry<Integer, Integer> entry : huaShiGangUserData.getBoxMap().entrySet()) {
                HuaShiGangProto.HuaShiGangBoxEntity.Builder box = HuaShiGangProto.HuaShiGangBoxEntity.newBuilder();
                box.setEventId(entry.getKey());
                box.setNum(entry.getValue());
                notifyBuilder.addBox(box);
            }
            HuaShiGangActivity activity = HuaShiGangMgr.getHuaShiGangActivity(activityId);
            List<HuaShiGangStrongPoint> pointList = activity.getUserNextPoints(huaShiGangUserData.getY());
            notifyBuilder.addAllRoute(HuaShiGangPb.getHuaShiGangStrongPointPbList(pointList));
            notifyBuilder.setBoxEventId(huaShiGangUserData.getBoxEventId());
            notifyBuilder.setCurTransportId(huaShiGangUserData.getTransportId());
            notifyBuilder.addAllTransportId(huaShiGangUserData.getTransportList());

            List<HuaShiGangMode> list = activity.getHuaShiGangModeList();

            // 总层数
            int size = list.size();
            int allFloor = size * 3;
            boolean boss = false;
            eHuaShiGangModeType modeType = list.get(size - 1).getModeType();
            if (modeType == eHuaShiGangModeType.C || modeType == eHuaShiGangModeType.D) {
                // 已经生成蔡京
                allFloor = allFloor - 3;
                boss = true;
            }

            notifyBuilder.setAllFloor(allFloor);
            notifyBuilder.setInBoss(boss);

            // 最近的掌柜数据
            HuaShiGangUserData lastData = activity.getLastHuaShiGangData();
            if (lastData.getUserId() > 0) {
                //TODO 设置Y值 及 最近掌柜信息
                PlayerProto.PlayerBaseTempMsg.Builder baseMsg = PlayerBasePb.parsePlayerBaseTempMsg(lastData.getUserBaseInfo());
                notifyBuilder.setLastY(lastData.getY());
                notifyBuilder.setLastPlayerInfo(baseMsg);
            }

            if (activity.getKillBossUserBaseInfo() != null) {
                notifyBuilder.setKillBossPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(activity.getKillBossUserBaseInfo()));
            }

            // 精英怪排行奖励红点
            List<Integer> redDot = activity.getEliteRewardRedDotList(serverId, playerId);
            notifyBuilder.addAllEliteRedDotList(redDot);

            // 神行千里
            notifyBuilder.setShenXing(activity.getNextShenXingY(huaShiGangUserData) != -1);

            // 开关
            notifyBuilder.addAllOpenSwitchType(huaShiGangUserData.getOpenSwitchList());

            // 当前所处阶段
            notifyBuilder.addAllBossYList(activity.huaShiGangData.getBossYList());

            // 当前位置中间boss的话，要给boss状态
            HuaShiGangMode mode = activity.getModeByY(huaShiGangUserData.getY());
            if (mode != null && mode.getModeType() == eHuaShiGangModeType.D && huaShiGangUserData.getMonsterId() > 0) {
                HuaShiGangMonsterData monsterData = activity.getHuaShiGangMonsterData(huaShiGangUserData.getX(), huaShiGangUserData.getY(), huaShiGangUserData.getMonsterId());
                if (monsterData != null) {
                    notifyBuilder.setBossDie(monsterData.getNowBlood() <= 0);
                }
            }
        }
        return notifyBuilder;
    }

    /**
     * 选择随机门客得到意外事件增益
     *
     * @param activityId
     * @param serverId
     * @param playerId
     * @param index
     */
    public static void chooseUnexpectedPatrons(int activityId, long serverId, long playerId, int index) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.ChooseUnexpectedPatronsRespMsg.Builder builder = HuaShiGangProto.ChooseUnexpectedPatronsRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_CHOOSE_PATRONS, builder));
            return;
        }

        int ret = huaShiGangActivity.chooseUnexpectedPatrons(serverId, playerId, index);
        builder.setRet(ret);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_CHOOSE_PATRONS, builder));
    }

    /**
     * 打开宝箱
     *
     * @param activityId
     * @param serverId
     * @param playerId
     * @param boxId
     */
    public static void openBox(int activityId, long serverId, long playerId, int boxId, int num) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.OpenBoxRespToGameServerMsg.Builder builder = HuaShiGangProto.OpenBoxRespToGameServerMsg.newBuilder();
        builder.setBoxId(boxId);
        builder.setNum(num);
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            builder.setReward("");
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(GameProtocol.S_HUA_SHI_GANG_OPEN_BOX_FROM_CROSS, builder));
            return;
        }

        ReturnData returnData = huaShiGangActivity.openBox(serverId, playerId, boxId, num);
        builder.setRet(returnData.getRet());
        builder.setReward(returnData.getRet() == 0 ? returnData.getParams().get(0) : "");
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(GameProtocol.S_HUA_SHI_GANG_OPEN_BOX_FROM_CROSS, builder));
    }

    /**
     * 解锁交通工具
     * @param activityId
     * @param serverId
     * @param playerId
     * @param transportId
     * @param builder
     */
    public static void unLockTransport(int activityId, long serverId, long playerId, int transportId, HuaShiGangProto.UnLockTransportRespToGameServerMsg.Builder builder) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return;
        }
        huaShiGangActivity.unLockTransport(serverId, playerId, transportId, builder);
    }

    /**
     * 更换交通工具
     *  @param activityId
     * @param serverId
     * @param playerId
     * @param transportId
     * @param builder
     */
    public static void changeTransport(int activityId, long serverId, long playerId, int transportId, HuaShiGangProto.ChangeTransportRespMsg.Builder builder) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return;
        }
        huaShiGangActivity.changeTransport(serverId, playerId, transportId, builder);
    }

    /**
     * 贸易事件
     *
     * @param activityId
     * @param serverId
     * @param playerId
     * @param eventId
     */
    public static void trade(int activityId, long serverId, long playerId, int eventId) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.TradeExchangeRespMsg.Builder builder = HuaShiGangProto.TradeExchangeRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_TRADE, builder));
            return;
        }

        int ret = huaShiGangActivity.trade(serverId, playerId, eventId);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_TRADE, builder));
            return;
        }
    }

    /**
     * 获取藏宝列表
     *
     * @param activityId
     * @param serverId
     * @param playerId
     */
    public static void getTreasureList(int activityId, long serverId, long playerId) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.GetTreasureListMsgRespMsg.Builder builder = HuaShiGangProto.GetTreasureListMsgRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_TRADE, builder));
            return;
        }

        int ret = huaShiGangActivity.getTreasureList(serverId, playerId);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_TRADE, builder));
            return;
        }
    }

    /**
     * 打开藏宝
     *
     * @param activityId
     * @param serverId
     * @param playerId
     * @param treasureId
     * @param userBaseInfo
     */
    public static void openTreasure(int activityId, long serverId, long playerId, int treasureId, UserBaseInfo userBaseInfo) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.OpenTreasureRespMsg.Builder builder = HuaShiGangProto.OpenTreasureRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_OPEN_TREASURE, builder));
            return;
        }

        int ret = huaShiGangActivity.openTreasure(serverId, playerId, treasureId, userBaseInfo);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_OPEN_TREASURE, builder));
        }
    }

    /**
     * 攻击怪物
     *
     * @param activityId
     * @param serverId
     * @param playerId
     * @param patronsId
     * @param ability
     * @param userBaseInfo
     * @param costNum
     */
    public static void attackMonster(int activityId, long serverId, long playerId, int patronsId, long ability, UserBaseInfo userBaseInfo, int costNum, int talentAddition, int occupationAddition, int bossTalentAddition) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.AttackMonsterFromCross.Builder builder = HuaShiGangProto.AttackMonsterFromCross.newBuilder();
        builder.setCostNum(costNum);
        builder.setIsKill(false);
        builder.setEventId(0);
        builder.setDamage(0);
        builder.setAddScore(0);
        builder.setNewBlood(0);
        builder.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(new UserBaseInfo()));
        builder.setTalentId(patronsId);
        builder.setActivityId(activityId);
        HuaShiGangUserData userData = huaShiGangActivity.getUserData(serverId, playerId);
        builder.setAllScore(userData == null ? 0 : userData.getAllScore());
        builder.setMonsterId(0);

        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(GameProtocol.S_HUA_SHI_GANG_ATTACK_MONSTER_FROM_CROSS, builder));
            return;
        }

        int ret = huaShiGangActivity.attackMonster(serverId, playerId, patronsId, ability, userBaseInfo, costNum, talentAddition, occupationAddition, bossTalentAddition);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(GameProtocol.S_HUA_SHI_GANG_ATTACK_MONSTER_FROM_CROSS, builder));
            return;
        }
    }

    /**
     * 查看怪物攻击榜单
     *
     * @param activityId
     * @param serverId
     * @param playerId
     */
    public static void getMonsterDamageList(int activityId, long serverId, long playerId) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_GET_ATTACK_RECORD, RankProto.RankListMsg.newBuilder()));
            return;
        }

        int ret = huaShiGangActivity.getMonsterDamageList(serverId, playerId);
        if (ret != 0) {
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_GET_ATTACK_RECORD, RankProto.RankListMsg.newBuilder()));
            return;
        }

    }

    /**
     * 精英怪伤害奖励排行
     */
    public static void getEliteMonsterDamageRank(int activityId, long serverId, long playerId, int y) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            HuaShiGangProto.GetEliteRankListRespMsg.Builder builder = HuaShiGangProto.GetEliteRankListRespMsg.newBuilder();
            builder.setRet(GameErrorCode.E_ACTIVITY_OVER_TIME);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_ELITE_RANK, builder));
            return;
        }

        int ret = huaShiGangActivity.getEliteMonsterDamageRank(serverId, playerId, y);
        if (ret != 0) {
            HuaShiGangProto.GetEliteRankListRespMsg.Builder builder = HuaShiGangProto.GetEliteRankListRespMsg.newBuilder();
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_ELITE_RANK, builder));
        }
    }

    /**
     * 获取攻击过的精英怪列表
     */
    public static void getAttackedEliteMonsterList(int activityId, long serverId, long playerId) {
        HuaShiGangProto.GetHuaShiGangEliteListRespMsg.Builder builder = HuaShiGangProto.GetHuaShiGangEliteListRespMsg.newBuilder();

        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_ATTACKED_ELITE_LIST, builder));
            return;
        }

        int ret = huaShiGangActivity.getAttackedEliteMonsterList(serverId, playerId);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_ATTACKED_ELITE_LIST, builder));
            return;
        }
    }

    /**
     * 获取精英怪排行奖励
     */
    public static void getEliteReward(int activityId, long serverId, long playerId, int y) {
        HuaShiGangProto.GetEliteRewardRespMsg.Builder builder = HuaShiGangProto.GetEliteRewardRespMsg.newBuilder();

        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_GET_ELITE_REWARD, builder));
            return;
        }

        int ret = huaShiGangActivity.getEliteReward(serverId, playerId, y);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_GET_ELITE_REWARD, builder));
        }
    }

    /**
     * 一键获取精英怪排行奖励
     */
    public static void getEliteRewardOneKey(int activityId, long serverId, long playerId) {
        HuaShiGangProto.GetEliteRewardRespMsg.Builder builder = HuaShiGangProto.GetEliteRewardRespMsg.newBuilder();

        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_GET_ELITE_REWARD, builder));
            return;
        }

        int ret = huaShiGangActivity.getEliteRewardOneKey(serverId, playerId);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_GET_ELITE_REWARD, builder));
        }
    }

    /**
     * 完成当前据点
     *
     * @param activityId
     * @param serverId
     * @param playerId
     */
    public static void completePoint(int activityId, long serverId, long playerId) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.HuaShiGangCompleteCurrentPointRespMsg.Builder builder = HuaShiGangProto.HuaShiGangCompleteCurrentPointRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_COMPLETE_POINT, builder));
            return;
        }

        int ret = huaShiGangActivity.completePoint(serverId, playerId);
        builder.setRet(ret);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_COMPLETE_POINT, builder));
    }

    /**
     * 神行千里
     *
     * @param activityId
     * @param serverId
     * @param playerId
     * @param userBaseInfo
     * @param type
     */
    public static void shenXing(int activityId, long serverId, long playerId, UserBaseInfo userBaseInfo, int type) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.ShenXingQianLiRespMsg.Builder builder = HuaShiGangProto.ShenXingQianLiRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_SHEN_XING, builder));
            return;
        }
        if (type == 0) {
            int ret = huaShiGangActivity.shenXing(serverId, playerId, userBaseInfo);
            if (ret != 0) {
                builder.setRet(ret);
                MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_SHEN_XING, builder));
                return;
            } else {
                builder.setRet(0);
                // 拼装数据
                MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_SHEN_XING, builder));
                MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_USER_DATA_NOTIFY, getHuaShiUserDataGangRespMsg(activityId, serverId, playerId)));
            }
        } else if (type == 1) {
            int ret = huaShiGangActivity.shenXingType1(serverId, playerId, userBaseInfo);
            if (ret != 0) {
                builder.setRet(ret);
                MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_SHEN_XING, builder));
                return;
            }
        }

    }

    /**
     * 花石纲获取怪物血量
     * @param activityId
     * @param serverId
     * @param playerId
     */
    public static void getHuaShiGangMonsterData(int activityId, long serverId, long playerId, UserScene userScene) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.GetHuaShiGangMonsterDataRespMsg.Builder builder = HuaShiGangProto.GetHuaShiGangMonsterDataRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_COMPLETE_POINT, builder));
            return;
        }

        int ret = huaShiGangActivity.getHuaShiGangMonsterData(serverId, playerId, userScene);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_COMPLETE_POINT, builder));
        }
    }

    /**
     * 同步能力值
     * @param activityId
     * @param serverId
     * @param ability
     */
    public static void notifyAbility(int activityId, long serverId, long ability) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        if (huaShiGangActivity == null) {
            getLogger().info("not activity {} {} {}", activityId, serverId, ability);
            return;
        }
        huaShiGangActivity.setAbility(serverId, ability);
    }

    public static void checkExpired() {
        List<Integer> expiredList = new ArrayList<>();
        for (HuaShiGangActivity activity : huaShiGangActivityMap.values()) {
            if ((activity.getActivityInfo().getEndShowTime() + 3 * 24 * 3600) < (System.currentTimeMillis() / 1000)) {
                expiredList.add(activity.getActivityInfo().getActivityId());
            }
        }
        for (int activityId : expiredList) {
            huaShiGangActivityMap.remove(activityId);
        }
    }

    /**
     * 所有点
     * @param activityId
     * @param serverId
     * @param playerId
     */
    public static void getAllPoints(int activityId, long serverId, long playerId) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        huaShiGangActivity.getAllPoints(serverId, playerId);
    }

    @Override
    public boolean reloadData() throws Exception {
        synchronized (this) {
            if (pointMap == null) {
                pointMap = new ConcurrentHashMap<>();
                pointMap.put(4, new Point(0, 1));
                pointMap.put(5, new Point(1, 1));
                pointMap.put(6, new Point(2, 1));
                pointMap.put(7, new Point(0, 2));
                pointMap.put(8, new Point(1, 2));
                pointMap.put(9, new Point(2, 2));
            }

            if (huaShiGangActivityMap == null) {
                huaShiGangActivityMap = new ConcurrentHashMap<>();
            }

            String nowTimeStr = DateHelper.getCurrentDateTimeString();
            List<Integer> activityTypeList = new ArrayList<>();
            activityTypeList.add(eActivityType.CrossHuaShiGangActivity.getValue());
            Map<Integer, ActivityInfo> activityInfoMap = ActivityBussiness.getOpenCrossRankActivityInfoMapByCrossServerId(activityTypeList, nowTimeStr, CrossBaseServer.getInstance().getServerId());

            // 加载数据库 加载配置.... 初始化花石纲数据
            for (ActivityInfo activityInfo : activityInfoMap.values()) {
                getHuaShiGangActivity(activityInfo);
            }

        }
        return true;
    }


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void main(String[] args) {
        if (pointMap == null) {
            pointMap = new ConcurrentHashMap<>();
            pointMap.put(4, new Point(0, 1));
            pointMap.put(5, new Point(1, 1));
            pointMap.put(6, new Point(2, 1));
            pointMap.put(7, new Point(0, 2));
            pointMap.put(8, new Point(1, 2));
            pointMap.put(9, new Point(2, 2));
        }

        int m = 27;
        int n = 4;
        Map<String, Integer> map = new HashMap<>();
        for (int j = 0; j < 100; j++) {
            // 组装多个单元
            List<HuaShiGangMode> huaShiGangModeList = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                huaShiGangModeList.addAll(getHuaShiGangUnit(n, huaShiGangModeList.size()));
            }
            for (HuaShiGangMode mode : huaShiGangModeList) {
                if (!map.containsKey(mode.getModeId().name())) {
                    map.put(mode.getModeId().name(), 0);
                }
                map.put(mode.getModeId().name(), map.get(mode.getModeId().name()) +1 );
            }
        }
        System.out.println(map);

//
//        checkAndBuildModeConnection(huaShiGangModeList);
//        printRoad(huaShiGangModeList);
//        System.out.println();
//        System.out.println();
//
//        checkAndBuildModeConnection(huaShiGangModeList);
//        printRoad(huaShiGangModeList);
//        System.out.println(JSON.toJSONString(huaShiGangModeList));
//
//        String zipString = ZipUtils.gzip(JSON.toJSONString(huaShiGangModeList));
//        System.out.println(zipString);
//        System.out.println(ZipUtils.gunzip(zipString));
//        List<HuaShiGangMode> x = JSONObject.parseArray(JSON.toJSONString(huaShiGangModeList), HuaShiGangMode.class);
//        System.out.println(JSON.toJSONString(x));

    }

    /**
     * 坐标key
     *
     * @param x
     * @param y
     * @return
     */
    public static String getKey(int x, int y) {
        StringBuilder str = new StringBuilder();
        str.append(x);
        str.append("-");
        str.append(y);
        return str.toString();
    }

    /**
     * 输出路线图
     *
     * @param huaShiGangModeList
     */
    public static void printRoad(List<HuaShiGangMode> huaShiGangModeList) {
        int size = huaShiGangModeList.size();
        for (int i = size - 1; i >= 0; i--) {
            HuaShiGangMode huaShiGangMode = huaShiGangModeList.get(i);
            for (int y = 2; y >= 0; y--) {
                for (int x = 0; x <= 2; x++) {
                    HuaShiGangStrongPoint huaShiGangStrongPoint = huaShiGangMode.getPoints()[x][y];
                    if (x == 2) {
                        System.out.printf(JSON.toJSONString(huaShiGangStrongPoint));
                    } else {
                        System.out.printf(JSON.toJSONString(huaShiGangStrongPoint) + "|");
                    }

                }
                System.out.println();
            }
        }
    }

    /**
     * 获取花石纲的单元
     *
     * @param aModeNum
     * @param srcSize  源模块数量
     * @return
     */
    public static List<HuaShiGangMode> getHuaShiGangUnit(int aModeNum, int srcSize) {
        List<HuaShiGangMode> huaShiGangModeList = new ArrayList<>();
        for (int i = 0; i < aModeNum; i++) {
            huaShiGangModeList.add(HuaShiGangBuildMode.getRandomAMode());
        }
        huaShiGangModeList.add(HuaShiGangBuildMode.getBMode());
        buildUnitInnerFloor(huaShiGangModeList, srcSize * 3);
        return huaShiGangModeList;
    }

    /**
     * 编排单元内层数
     *
     * @param huaShiGangModeList
     * @param yAdd
     */
    public static void buildUnitInnerFloor(List<HuaShiGangMode> huaShiGangModeList, int yAdd) {
        int modeNum = huaShiGangModeList.size();
        for (int floor = 0; floor < modeNum; floor++) {
            HuaShiGangMode huaShiGangMode = huaShiGangModeList.get(floor);
            for (HuaShiGangStrongPoint[] huaShiGangStrongPoints : huaShiGangMode.getPoints()) {
                for (HuaShiGangStrongPoint huaShiGangStrongPoint : huaShiGangStrongPoints) {
                    if (huaShiGangStrongPoint != null) {
                        huaShiGangStrongPoint.setY(huaShiGangStrongPoint.getY() + floor * 3 + yAdd);
                        for (Point point : huaShiGangStrongPoint.getNextList()) {
                            point.setLocation(point.x, point.y + floor * 3 + yAdd);
                        }
                    }
                }
            }
        }
    }

    /**
     * 检查模块间的连接方式 没有连接的生成连接方式
     *
     * @param huaShiGangModeList
     */
    public static boolean checkAndBuildModeConnection(List<HuaShiGangMode> huaShiGangModeList) {

        boolean stat = false;
        // 编排层数 从低到高 修改y的值
        int modeNum = huaShiGangModeList.size();
        for (int floor = 0; floor < modeNum; floor++) {
            HuaShiGangMode huaShiGangMode = huaShiGangModeList.get(floor);

            // 判断模块尾部是否有下一个连接点
            if (floor + 1 < modeNum && huaShiGangMode.getPoints()[0][2] != null && huaShiGangMode.getPoints()[0][2].getNextList().size() == 0) {
                int bn = huaShiGangMode.getTopNum();
                int tn = huaShiGangModeList.get(floor + 1).getBottomNum();
                Map<Integer, List<Integer>> connectionMap = HuaShiGangModeConnection.getRandomConnection(bn, tn);
                for (Map.Entry<Integer, List<Integer>> entry : connectionMap.entrySet()) {
                    for (int xAdd : entry.getValue()) {
                        HuaShiGangStrongPoint huaShiGangStrongPoint = huaShiGangMode.getPoints()[entry.getKey()][2];
                        huaShiGangStrongPoint.addNextPoint(new Point(huaShiGangStrongPoint.getX() + xAdd, huaShiGangStrongPoint.getY() + 1));
                        stat = true;
                    }
                }
            }
        }
        return stat;
    }

    @Override
    public boolean save() {
        for (HuaShiGangActivity huaShiGangActivity : huaShiGangActivityMap.values()) {
            huaShiGangActivity.save();
        }
        return true;
    }

    public boolean removeExpireData(){
        try {
            getLogger().info("移除花石纲过期活动" + huaShiGangActivityMap.size());
            List<Integer> removeList = new ArrayList<>();
            for (Integer key : huaShiGangActivityMap.keySet()) {
                if(huaShiGangActivityMap.get(key).getActivityInfo() == null){
                    removeList.add(key);
                    continue;
                }
                if (System.currentTimeMillis() >= huaShiGangActivityMap.get(key).getActivityInfo().getEndShowTime() * 1000 + 12 * 3600 * 1000) {
                    removeList.add(key);
                }
            }
            getLogger().info("移除花石纲过期活动"+removeList.size());
            for(Integer removeKey : removeList){
                huaShiGangActivityMap.remove(removeKey);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 修改自动处理开关
     */
    public static void updateOpenSwitch(int activityId, long serverId, long playerId, List<Integer> openSwitchList) {
        HuaShiGangActivity huaShiGangActivity = getHuaShiGangActivity(activityId);
        HuaShiGangProto.UpdateAutoEventSwitchRespMsg.Builder builder = HuaShiGangProto.UpdateAutoEventSwitchRespMsg.newBuilder();
        if (huaShiGangActivity == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_UPDATE_AUTO_EVENT_SWITCH, builder));
            return;
        }
        int ret = huaShiGangActivity.updateOpenSwitch(serverId, playerId, openSwitchList);
        if (ret != 0) {
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_UPDATE_AUTO_EVENT_SWITCH, builder));
            return;
        } else {
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_USER_DATA_NOTIFY, getHuaShiUserDataGangRespMsg(activityId, serverId, playerId)));
            // 拼装数据
            builder.setRet(0);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(ClientProtocol.U_HUA_SHI_GANG_UPDATE_AUTO_EVENT_SWITCH, builder));
        }
    }
}
